package com.company.exam8;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTask implements Runnable {
    private String saveFilePath;// 存储下载文件的位置
    private URL url;// 下载文件的路径
    private long startLocation;
    private long endLocation;

    public DownloadTask(String saveFilePath, URL url, long startLocation,
                        long endLocation) {
        super();
        this.saveFilePath = saveFilePath;
        this.url = url;
        this.startLocation = startLocation;
        this.endLocation = endLocation;
    }

    @Override
    public void run() {
        HttpURLConnection httpConn = null;
        try {
            httpConn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            System.err.println("连接资源地址失败");
            throw new RuntimeException("连接资源地址失败", e);
        }
        RandomAccessFile raf = null;//RandowAccessFile类是用来访问那些保存数据文件，
        //这里不太人性的是需要自己首先在本地创建文件夹。
        try {
            raf = new RandomAccessFile(saveFilePath, "rwd");//rwd：可读可写可后缀
            raf.seek(startLocation);//访问文件指定位置，并进行读写
            System.out.println("创建下载资源成功");
        } catch (Exception e) {
            System.err.println("创建下载资源失败");
            throw new RuntimeException("创建下载资源失败", e);
        }
        long downloadLength = 0;
        try {
            BufferedInputStream in = new BufferedInputStream(
                    httpConn.getInputStream());//httpConn.getInputStrean:得到资源的输入流
            byte[] bs = new byte[1024 * 1024];
            int len = -1;
            while ((len = in.read(bs)) != -1) {
                raf.write(bs, 0, len);
                downloadLength += len;
            }
            System.out.println(Thread.currentThread().getName() + "下载区间:"
                    + startLocation + "-" + endLocation + "下载的数量是:"
                    + downloadLength);
            in.close();
            raf.close();
        } catch (IOException e) {
            System.err.println("取到下载资源失败");
            throw new RuntimeException("取到下载资源失败", e);
        }
    }
}

